<template>
  <div class="hotel-daily-summary">
    <!-- 顶部搜索区域 -->
    <div class="top-section">
      <div class="header-wrapper">
        <h3 class="title">酒店日报</h3>
      </div>
      <div class="form-wrapper">
        <div class="form-content">
          <!-- 日期范围 -->
          <div class="form-item">
            <span class="label">时段</span>
            <a-range-picker v-model:value="currentDateRange" :placeholder="['开始日期', '结束日期']" style="width: 260px">
              <template #suffixIcon>
                <calendar-outlined />
              </template>
            </a-range-picker>
          </div>

          <!-- 启动对比开关 -->
          <div class="form-item form-item-center">
            <span class="label">启动对比</span>
            <a-switch v-model:checked="contrastEnabled" @change="onContrastChange" />
          </div>

          <!-- 查询 / 重置 / 筛选 按钮 -->
          <div class="form-item">
            <a-button type="primary" @click="handleSearch">查询</a-button>
            <a-button style="margin-left: 8px" @click="handleReset">重置</a-button>
            <div class="filter-icon-container">
              <img class="icon-screen" src="/@/assets/images/screening.png" @click="showFilter = true" alt="筛选图标" :title="'过滤设置'" />
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 主内容区域 -->
    <div class="main-content"> 餐饮收入 </div>
    <div class="hotel-daily-m-main">
      <div style="min-width: 200px; height: 100%; background: #faf9fc">
        <div class="hotel-daily-main-project">项目</div>
        <div class="hotel-daily-main-left" v-for="item in summaryRankList">{{ item.name }}</div>
      </div>
      <div style="min-width: 1360px; height: 100%; display: flex; flex-direction: row; margin-left: 10px">
        <div style="width: 30%">
          <div class="hotel-daily-main-right-0">
            <div class="hotel-daily-main-title0">
              <div class="hotel-daily-main-title">餐饮收入</div>
              <div class="hotel-daily-main-1-0">
                <div class="hotel-daily-main-1-1">实际</div>
              </div>
              <div class="hotel-daily-detail-0-1" style="width: 100%; margin: 5px 0">
                <div class="hotel-daily-detail-0-2">万元</div>
              </div>
            </div>
          </div>
          <div class="hotel-daily-detail-0-1" v-for="item in summaryRankList" style="margin: 5px 0 0 0">
            <div class="hotel-daily-detial-1-2">{{ item.price }}</div>
          </div>
        </div>
        <div style="width: 30%; margin-left: 5px">
          <div class="hotel-daily-main-right-0">
            <div class="hotel-daily-main-title0">
              <div class="hotel-daily-main-title">对比预算</div>
              <div class="hotel-daily-main-1-0">
                <div class="hotel-daily-main-shouru-1-1-2">预算</div>
                <div class="hotel-daily-main-shouru-1-2-2">完成率</div>
              </div>
              <div class="hotel-daily-detail-0-1" style="width: 100%; margin: 5px 0">
                <div class="hotel-daily-detail-0-2-2-first">万元</div>
                <div class="hotel-daily-detail-0-2-2-last">%</div>
              </div>
            </div>
          </div>
          <div class="hotel-daily-detail-0-1" v-for="item in summaryRankList" style="margin: 5px 0 0 0">
            <div class="hotel-daily-detial-1-2-first">{{ item.revenueBudget }}</div>
            <div class="hotel-daily-detial-1-2-last">{{ item.comRate }}</div>
          </div>
        </div>
        <div style="width: 30%; margin-left: 5px">
          <div class="hotel-daily-main-right-0">
            <div class="hotel-daily-main-title0">
              <div class="hotel-daily-main-title">对比去年</div>
              <div class="hotel-daily-main-1-0">
                <div class="hotel-daily-main-shouru-1-1-2">去年</div>
                <div class="hotel-daily-main-shouru-1-2-2">增长率</div>
              </div>
              <div class="hotel-daily-detail-0-1" style="width: 100%; margin: 5px 0">
                <div class="hotel-daily-detail-0-2-2-first">万元</div>
                <div class="hotel-daily-detail-0-2-2-last">%</div>
              </div>
            </div>
          </div>
          <div class="hotel-daily-detail-0-1" v-for="item in summaryRankList" style="margin: 5px 0 0 0">
            <div class="hotel-daily-detial-1-2-first">{{ item.lyear }}</div>
            <div class="hotel-daily-detial-1-2-last">{{ item.growthRate }}</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 过滤筛选弹窗 -->
    <SearchFilterModal v-if="showFilter" v-model:visible="showFilter" :fields="filterFields" @save="confirmFilter" />
  </div>
</template>

<script>
import dayjs from 'dayjs';
import { Collapse, Form, DatePicker, Button, Switch, message } from 'ant-design-vue';
import { CalendarOutlined } from '@ant-design/icons-vue';
import { defHttp } from '/@/utils/http/axios';
import * as MathUtil from '/@/utils/MathUtil';
import TableCard from '/@/views/applications/ui/TableCard.vue';
import SearchFilterModal from '/@/views/applications/ui/SearchFilterModal.vue';
import { ref, onMounted, nextTick } from 'vue';
import { percent2DFormatter } from '/@/utils/MathUtil';

export default {
  name: 'HotelDailyOverview2',

  components: {
    ACollapse: Collapse,
    AForm: Form,
    AFormItem: Form.Item,
    ARangePicker: DatePicker.RangePicker,
    ASwitch: Switch,
    AButton: Button,
    CalendarOutlined,
    TableCard,
    SearchFilterModal,
  },

  setup() {
    const loading = ref(false);
    const showFilter = ref(false);
    const handleTableChange = (pagination, filters, sorter) => {
      console.log('Table changed:', pagination, filters, sorter);
    };
    // 日期范围，初始为昨天～昨天
    const currentDateRange = ref([dayjs().subtract(60, 'day'), dayjs().subtract(1, 'day')]);
    // 对比开关、以及对比区间
    const contrastEnabled = ref(false);
    const currentContrastRange = ref([]);

    // 酒店列表（从后端拿到的所有酒店），以及选中的 code（逗号拼接）
    const hotelList = ref([]);
    const currentHotel = ref('');

    // 各个表格需要的数据
    const summaryRankList = ref([]);
    const roomRankList = ref([]);
    const fbRankList = ref([]);
    const buffetRankList = ref([]);
    const cnRankList = ref([]);
    const spRankList = ref([]);
    const bhRankList = ref([]);
    const osRankList = ref([]);
    const otherRankList = ref([]);
    const occRankList = ref([]);
    const priceRankList = ref([]);
    const perRevenueRankList = ref([]);

    // 表格滚动配置
    const tableHigh = ref({ x: '100%', y: 'calc(60vh)' });

    // 右侧可配置的筛选字段
    const filterFields = ref([
      { value: 'date', label: '时段', selected: true, showDetails: true },
      { value: 'contrast', label: '启动对比', selected: false, showDetails: true },
      { value: 'contrastDate', label: '对比时段', selected: false, showDetails: true },
    ]);

    // 初始化酒店列表：调用 /data/hotel/list 接口
    const initHotelList = async () => {
      try {
        const res = await defHttp.get({ url: '/data/hotel/list' }, { isTransformResponse: false });
        if (res.result && Array.isArray(res.result) && res.result.length) {
          hotelList.value = res.result.map((h) => ({ code: h.code, name: h.name }));
          // 默认把所有 code 用逗号拼起来
          currentHotel.value = hotelList.value.map((h) => h.code).join(',');
          fetchBaseInfo();
        } else {
          message.error('获取酒店列表失败');
        }
      } catch {
        message.error('获取酒店列表网络请求失败');
      }
    };

    const fetchBaseInfo = async () => {
      if (!currentHotel.value) {
        message.warning('请先选择酒店');
        return;
      }
      loading.value = true;

      try {
        const res = await defHttp.post(
          {
            url: '/data/query',
            data: {
              labelCode: 'getHotelDailySummary', // 明确指定查询类型
              params: [],
              sqlParams: [
                { key: 'code', value: currentHotel.value },
                {
                  key: 'beginDate',
                  value: currentDateRange.value[0].format('YYYY-MM-DD'),
                },
                {
                  key: 'endDate',
                  value: currentDateRange.value[1].format('YYYY-MM-DD'),
                },
                // 对比日期参数
                ...(contrastEnabled.value
                  ? [
                    {
                      key: 'beginContrastDate',
                      value: currentContrastRange.value[0].format('YYYY-MM-DD'),
                    },
                    {
                      key: 'endContrastDate',
                      value: currentContrastRange.value[1].format('YYYY-MM-DD'),
                    },
                  ]
                  : [
                    { key: 'beginContrastDate', value: 'x' },
                    { key: 'endContrastDate', value: 'x' },
                  ]),
              ],
              pageIndex: 1,
              pageSize: 100,
            },
          },
          { isTransformResponse: false }
        );

        console.log('API完整响应:', res);

        // 统一响应处理逻辑
        if (res.code !== 200 || res.result === 'fail') {
          throw new Error(res.message || '请求失败');
        }

        // 兼容两种数据返回格式
        const rawData = res.result?.datas?.data || res.result?.data || [];
        if (rawData.length === 0) {
          message.warning('没有查询到数据');
          clearAllLists();
          return;
        }
        processRawData(rawData);
      } catch (error) {
        console.error('请求失败:', error);
        message.error(error.message || '查询数据失败');
        clearAllLists();
      } finally {
        loading.value = false;
      }
    };
    // 处理后端返回的原始数组
    const processRawData = (data) => {
      console.log('原始数据:', data); // 调试用，查看原始数据结构
      if (!data || !Array.isArray(data)) {
        console.warn('无效的数据格式');
        clearAllLists();
        return;
      }

      const processedData = data
        .filter((item) => item !== null && item !== undefined) // 过滤无效项
        .map((item) => {
          // 检查关键属性是否存在
          if (!item.hotelCode && !item.hotelShortName && !item.hotelName) {
            console.warn('跳过无效酒店数据项:', item);
            return null;
          }

          // 构建基础数据对象，确保所有需要的字段都存在
          const baseItem = {
            // 基础字段
            key: item.hotelCode || item.hotelShortName || item.hotelName || '未命名酒店',
            name: item && (item.hotelShortName || item.hotelName) ? item.hotelShortName || item.hotelName : '未命名酒店',

            // 客房相关数据
            actualSrooms: item.actualSrooms || 0,
            actualCrooms: item.actualCrooms || 0,
            occRate: MathUtil.safeDivide(item.actualSrooms, item.actualCrooms),
            price: MathUtil.safeDivide(item.roomRevenue, item.actualSrooms),
            perRevenue: MathUtil.safeDivide(item.roomRevenue, item.actualCrooms),

            // 收入相关数据
            revenue: item.revenue || 0,
            roomRevenue: item.roomRevenue || 0,
            fbRevenue: item.fbRevenue || 0,
            cnRevenue: item.cnRevenue || 0,
            spRevenue: item.spRevenue || 0,
            bhRevenue: item.bhRevenue || 0,
            osRevenue: item.osRevenue || 0,
            otherRevenue: item.otherRevenue || 0,
            // 预算相关
            revenueBudget: item.revenueBudget || 0,
            roomRevenueBudget: item.roomRevenueBudget || 0,
            fbRevenueBudget: item.fbRevenueBudget || 0,
            buffetRevenueBudget: item.buffetRevenueBudget || 0,
            cnRevenueBudget: item.cnRevenueBudget || 0,
            spRevenueBudget: item.spRevenueBudget || 0,
            bhRevenueBudget: item.bhRevenueBudget || 0,
            osRevenueBudget: item.osRevenueBudget || 0,
            otherRevenueBudget: item.otherRevenueBudget || 0,

            // 新增：确保所有需要的预算属性都存在
            sroomsBudget: item.sroomsBudget || 0,
            croomsBudget: item.croomsBudget || 0,
            // monthSroomsBudget: item.monthSroomsBudget || 0,
            // monthCroomsBudget: item.monthCroomsBudget || 0,
            // yearSroomsBudget: item.yearSroomsBudget || 0,
            // yearCroomsBudget: item.yearCroomsBudget || 0,

            // 对比数据
            contrastRevenue: item.contrastRevenue || 0,
            lyearRevenue: item.lyearRevenue || 0,
            lyearRoomRevenue: item.lyearRoomRevenue || 0,
            lyearFbRevenue: item.lyearFbRevenue || 0,
            lyearBuffetRevenue: item.lyearBuffetRevenue || 0,
            lyearCnRevenue: item.lyearCnRevenue || 0,
            lyearSpRevenue: item.lyearSpRevenue || 0,
            lyearBhRevenue: item.lyearBhRevenue || 0,
            lyearOsRevenue: item.lyearOsRevenue || 0,
            lyearOtherRevenue: item.lyearOtherRevenue || 0,
            lyearActualSrooms: item.lyearActualSrooms || 0,
            lyearActualCrooms: item.lyearActualCrooms || 0,

            // 月度数据
            monthRevenue: item.monthRevenue || 0,
            monthBudget: item.monthBudget || 0,
            monthCroomsBudget: item.monthCroomsBudget || 0,
            monthSroomsBudget: item.monthSroomsBudget || 0,
            monthRoomRevenueBudget: item.monthRoomRevenueBudget || 0,
            monthFbRevenueBudget: item.monthFbRevenueBudget || 0,
            monthBuffetRevenueBudget: item.monthBuffetRevenueBudget || 0,
            monthCnRevenueBudget: item.monthCnRevenueBudget || 0,
            monthSpRevenueBudget: item.monthSpRevenueBudget || 0,
            monthBhRevenueBudget: item.monthBhRevenueBudget || 0,
            monthOsRevenueBudget: item.monthOsRevenueBudget || 0,
            monthOtherRevenueBudget: item.monthOtherRevenueBudget || 0,

            // 年度数据
            yearRevenue: item.yearRevenue || 0,
            yearBudget: item.yearBudget || 0,
            yearCroomsBudget: item.yearCroomsBudget || 0,
            yearSroomsBudget: item.yearSroomsBudget || 0,
            yearRoomRevenueBudget: item.yearRoomRevenueBudget || 0,
            yearFbRevenueBudget: item.yearFbRevenueBudget || 0,
            yearBuffetRevenueBudget: item.yearBuffetRevenueBudget || 0,
            yearCnRevenueBudget: item.yearCnRevenueBudget || 0,
            yearSpRevenueBudget: item.yearSpRevenueBudget || 0,
            yearBhRevenueBudget: item.yearBhRevenueBudget || 0,
            yearOsRevenueBudget: item.yearOsRevenueBudget || 0,
            yearOtherRevenueBudget: item.yearOtherRevenueBudget || 0,

            // 计算字段
            comRate: MathUtil.percent2DFormatter(MathUtil.safeDivide(item.revenue, item.revenueBudget), 0),
            growthRate: MathUtil.diffPercent2Formatter(item.revenue, item.lyearRevenue, 0),
            comMonthRate: MathUtil.safeDivide(item.monthRevenue, item.monthBudget),
            comYearRate: MathUtil.percent2DFormatter(MathUtil.safeDivide(item.yearRevenue, item.yearBudget), 0),
          };

          // 确保 map 方法返回数据对象
          return baseItem;
        })
        .filter(Boolean); // 过滤掉 null 值
      console.log('处理后的数据:', processedData); // 调试用，查看处理结果
      // 更新各个列表
      if (processedData.length > 0) {
        summaryRankList.value = processedData;

        // 客房收入情况
        // roomRankList.value = processedData.map((item) => ({
        //   key: item.key,
        //   name: item.name,
        //   actual: item.roomRevenue,
        //   budget: item.roomRevenueBudget,
        //   comRate: MathUtil.safeDivide(item.roomRevenue, item.roomRevenueBudget || 1),
        //   lyear: item.lyearRoomRevenue,
        //   growthRate: MathUtil.diffPercent2Formatter(item.roomRevenue, item.lyearRoomRevenue, 0),
        // }));

        // 入住率
        // occRankList.value = processedData.map((item) => ({
        //   key: item.key,
        //   name: item.name,
        //   actual: item.occRate,
        //   budget: MathUtil.safeDivide(item.sroomsBudget, item.croomsBudget || 1),
        //   comRate: MathUtil.safeDivide(item.occRate, MathUtil.safeDivide(item.sroomsBudget, item.croomsBudget || 1)),
        //   lyear: MathUtil.safeDivide(item.lyearActualSrooms, item.lyearActualCrooms || 1),
        //   growthRate: MathUtil.diffPercent2Formatter(
        //     MathUtil.safeDivide(item.actualSrooms, item.actualCrooms),
        //     MathUtil.safeDivide(item.lyearActualSrooms, item.lyearActualCrooms || 1),
        //     0
        //   ),
        //   actualSrooms: item.actualSrooms,
        //   actualCrooms: item.actualCrooms,
        //   sroomsBudget: item.sroomsBudget,
        //   croomsBudget: item.croomsBudget,
        //   lyearActualSrooms: item.lyearActualSrooms,
        //   lyearActualCrooms: item.lyearActualCrooms,
        // }));

        // 平均房价
        // priceRankList.value = processedData.map((item) => ({
        //   key: item.key,
        //   name: item.name,
        //   actual: item.price,
        //   budget: MathUtil.safeDivide(item.roomRevenueBudget, item.sroomsBudget || 1),
        //   comRate: MathUtil.safeDivide(item.price, MathUtil.safeDivide(item.roomRevenueBudget, item.sroomsBudget || 1)),
        //   lyear: MathUtil.safeDivide(item.lyearRoomRevenue, item.lyearActualSrooms || 1),
        //   growthRate: MathUtil.diffPercent2Formatter(
        //     MathUtil.safeDivide(item.roomRevenue, item.actualSrooms || 1),
        //     MathUtil.safeDivide(item.lyearRoomRevenue, item.lyearActualSrooms || 1),
        //     0
        //   ),
        //   roomRevenue: item.roomRevenue,
        //   actualSrooms: item.actualSrooms,
        //   roomRevenueBudget: item.roomRevenueBudget,
        //   sroomsBudget: item.sroomsBudget,
        //   lyearRoomRevenue: item.lyearRoomRevenue,
        //   lyearActualSrooms: item.lyearActualSrooms,
        // }));

        // 每房收益
        // perRevenueRankList.value = processedData.map((item) => ({
        //   key: item.key,
        //   name: item.name,
        //   actual: item.perRevenue,
        //   budget: MathUtil.safeDivide(item.roomRevenueBudget, item.croomsBudget || 1),
        //   comRate: MathUtil.safeDivide(item.perRevenue, MathUtil.safeDivide(item.roomRevenueBudget, item.croomsBudget || 1)),
        //   lyear: MathUtil.safeDivide(item.lyearRoomRevenue, item.lyearActualCrooms || 1),
        //   growthRate: MathUtil.diffPercent2Formatter(
        //     MathUtil.safeDivide(item.roomRevenue, item.actualCrooms || 1),
        //     MathUtil.safeDivide(item.lyearRoomRevenue, item.lyearActualCrooms || 1),
        //     0
        //   ),
        //   roomRevenue: item.roomRevenue,
        //   actualCrooms: item.actualCrooms,
        //   roomRevenueBudget: item.roomRevenueBudget,
        //   croomsBudget: item.croomsBudget,
        //   lyearRoomRevenue: item.lyearRoomRevenue,
        //   lyearActualCrooms: item.lyearActualCrooms,
        // }));

        // 餐饮收入情况
        // fbRankList.value = processedData.map((item) => ({
        //   key: item.key,
        //   name: item.name,
        //   actual: item.fbRevenue,
        //   budget: item.fbRevenueBudget,
        //   comRate: MathUtil.safeDivide(item.fbRevenue, item.fbRevenueBudget || 1),
        //   lyear: item.lyearFbRevenue,
        //   growthRate: MathUtil.diffPercent2Formatter(item.fbRevenue, item.lyearFbRevenue, 0),
        // }));
        //
        // buffetRankList.value = processedData.map((item) => ({
        //   key: item.key,
        //   name: item.name,
        //   actual: item.buffetRevenue,
        //   budget: item.buffetRevenueBudget,
        //   comRate: MathUtil.safeDivide(item.buffetRevenue, item.buffetRevenueBudget || 1),
        //   lyear: item.lyearBuffetRevenue,
        //   growthRate: MathUtil.diffPercent2Formatter(item.buffetRevenue, item.lyearBuffetRevenue, 0),
        // }));
        //
        // cnRankList.value = processedData.map((item) => ({
        //   key: item.key,
        //   name: item.name,
        //   actual: item.cnRevenue,
        //   budget: item.cnRevenueBudget,
        //   comRate: MathUtil.safeDivide(item.cnRevenue, item.cnRevenueBudget || 1),
        //   lyear: item.lyearCnRevenue,
        //   growthRate: MathUtil.diffPercent2Formatter(item.cnRevenue, item.lyearCnRevenue, 0),
        // }));

        // spRankList.value = processedData.map((item) => ({
        //   key: item.key,
        //   name: item.name,
        //   actual: item.spRevenue,
        //   budget: item.spRevenueBudget,
        //   comRate: MathUtil.safeDivide(item.spRevenue, item.spRevenueBudget || 1),
        //   lyear: item.lyearSpRevenue,
        //   growthRate: MathUtil.diffPercent2Formatter(item.spRevenue, item.lyearSpRevenue, 0),
        // }));

        // bhRankList.value = processedData.map((item) => ({
        //   key: item.key,
        //   name: item.name,
        //   actual: item.bhRevenue,
        //   budget: item.bhRevenueBudget,
        //   comRate: MathUtil.safeDivide(item.bhRevenue, item.bhRevenueBudget || 1),
        //   lyear: item.lyearBhRevenue,
        //   growthRate: MathUtil.diffPercent2Formatter(item.bhRevenue, item.lyearBhRevenue, 0),
        // }));

        // osRankList.value = processedData.map((item) => ({
        //   key: item.key,
        //   name: item.name,
        //   actual: item.osRevenue,
        //   budget: item.osRevenueBudget,
        //   comRate: MathUtil.safeDivide(item.osRevenue, item.osRevenueBudget || 1),
        //   lyear: item.lyearOsRevenue,
        //   growthRate: MathUtil.diffPercent2Formatter(item.osRevenue, item.lyearOsRevenue, 0),
        // }));

        // 其他收入情况
        // otherRankList.value = processedData.map((item) => ({
        //   key: item.key,
        //   name: item.name,
        //   actual: item.otherRevenue,
        //   budget: item.otherRevenueBudget,
        //   comRate: MathUtil.safeDivide(item.otherRevenue, item.otherRevenueBudget || 1),
        //   lyear: item.lyearOtherRevenue,
        //   growthRate: MathUtil.diffPercent2Formatter(item.otherRevenue, item.lyearOtherRevenue, 0),
        // }));
      } else {
        clearAllLists();
      }
    };
    // 清空各个列表
    const clearAllLists = () => {
      nextTick(() => {
        summaryRankList.value = [];
        // roomRankList.value = [];
        // fbRankList.value = [];
        // buffetRankList.value = [];
        // cnRankList.value = [];
        // spRankList.value = [];
        // bhRankList.value = [];
        // osRankList.value = [];
        // otherRankList.value = [];
        // occRankList.value = [];
        // priceRankList.value = [];
        // perRevenueRankList.value = [];
      });
    };

    // 列配置：数据汇总
    const summaryRankColumns = [
      {
        title: '项目',
        dataIndex: 'name',
        key: 'name',
        width: 120,
        align: 'left',
        fixed: 'left',
      },
      {
        title: '入住率',
        dataIndex: 'occRate',
        key: 'occRate',
        width: 90,
        align: 'right',
        customRender: ({ text }) => {
          const num = Number(text) || 0;
          return MathUtil.percent2DFormatter(num, 0);
        },
      },
      {
        title: '平均房价',
        dataIndex: 'price',
        key: 'price',
        width: 90,
        align: 'right',
        customRender: ({ text }) => {
          const num = Number(text) || 0;
          return MathUtil.currencyWFormatter(num, 0);
        },
      },
      {
        title: '总收入',
        dataIndex: 'revenue',
        key: 'revenue',
        width: 90,
        align: 'right',
        customRender: ({ text }) => {
          const num = Number(text) || 0;
          return MathUtil.currencyWFormatter(num, 0);
        },
      },
      {
        title: '对比收入',
        dataIndex: 'contrastRevenue',
        key: 'contrastRevenue',
        width: 90,
        align: 'right',
        customRender: ({ text }) => {
          const num = Number(text) || 0;
          return MathUtil.currencyWFormatter(num, 0);
        },
      },
      {
        title: '预算',
        dataIndex: 'revenueBudget',
        key: 'revenueBudget',
        width: 90,
        align: 'right',
        customRender: ({ text }) => {
          const num = Number(text) || 0;
          return MathUtil.currencyWFormatter(num, 0);
        },
      },
      {
        title: '完成率',
        dataIndex: 'comRate',
        key: 'comRate',
        width: 90,
        align: 'right',
        customRender: ({ text }) => {
          const num = Number(text) || 0;
          return MathUtil.percent2DFormatter(num, 0);
        },
      },
      {
        title: '上年同期',
        dataIndex: 'lyear',
        key: 'lyear',
        width: 90,
        align: 'right',
        customRender: ({ text }) => {
          const num = Number(text) || 0;
          return MathUtil.currencyWFormatter(num, 0);
        },
      },
      {
        title: '增长率',
        dataIndex: 'growthRate',
        key: 'growthRate',
        width: 90,
        align: 'right',
        customRender: ({ text }) => {
          const num = Number(text);
          return num != null && !isNaN(num) ? `${num.toFixed(0)}%` : '-';
        },
      },
      {
        title: '月进度',
        dataIndex: 'comMonthRate',
        key: 'comMonthRate',
        width: 90,
        align: 'right',
        customRender: ({ text }) => {
          const num = Number(text) || 0;
          return MathUtil.percent2DFormatter(num, 0);
        },
      },
      {
        title: '年进度',
        dataIndex: 'comYearRate',
        key: 'comYearRate',
        width: 90,
        align: 'right',
        customRender: ({ text }) => {
          const num = Number(text) || 0;
          return MathUtil.percent2DFormatter(num, 0);
        },
      },
    ];

    // 通用"实际 vs 预算 vs 上年同期 vs 增长率"表格列
    const rankColumns = [
      {
        title: '项目',
        dataIndex: 'name',
        key: 'name',
        width: 120,
        align: 'left',
        fixed: 'left',
      },
      {
        title: '实际',
        dataIndex: 'actual',
        key: 'actual',
        width: 80,
        align: 'right',
        customRender: ({ text }) => {
          const num = Number(text) || 0;
          return MathUtil.currencyWFormatter(num, 0);
        },
      },
      {
        title: '预算',
        dataIndex: 'budget',
        key: 'budget',
        width: 80,
        align: 'right',
        customRender: ({ text }) => {
          const num = Number(text) || 0;
          return MathUtil.currencyWFormatter(num, 0);
        },
      },
      {
        title: '完成率',
        dataIndex: 'comRate',
        key: 'comRate',
        width: 80,
        align: 'right',
        customRender: ({ text }) => {
          const num = Number(text) || 0;
          return MathUtil.percent2DFormatter(num, 0);
        },
      },
      {
        title: '上年同期',
        dataIndex: 'lyear',
        key: 'lyear',
        width: 80,
        align: 'right',
        customRender: ({ text }) => {
          const num = Number(text) || 0;
          return MathUtil.currencyWFormatter(num, 0);
        },
      },
      {
        title: '增长率',
        dataIndex: 'growthRate',
        key: 'growthRate',
        width: 80,
        align: 'right',
        customRender: ({ text }) => {
          const num = Number(text);
          return num != null && !isNaN(num) ? `${num.toFixed(0)}%` : '-';
        },
      },
    ];

    // 入住率那块
    const occRankColumns = [
      {
        title: '项目',
        dataIndex: 'name',
        key: 'name',
        width: 120,
        align: 'left',
        fixed: 'left',
      },
      {
        title: '实际',
        dataIndex: 'actual',
        key: 'actual',
        width: 80,
        align: 'right',
        customRender: ({ text }) => {
          const num = Number(text) || 0;
          return MathUtil.percent2DFormatter(num, 0);
        },
      },
      {
        title: '预算',
        dataIndex: 'budget',
        key: 'budget',
        width: 80,
        align: 'right',
        customRender: ({ text }) => {
          const num = Number(text) || 0;
          return MathUtil.percent2DFormatter(num, 0);
        },
      },
      {
        title: '完成率',
        dataIndex: 'comRate',
        key: 'comRate',
        width: 80,
        align: 'right',
        customRender: ({ text }) => {
          const num = Number(text) || 0;
          return MathUtil.percent2DFormatter(num, 0);
        },
      },
      {
        title: '上年同期',
        dataIndex: 'lyear',
        key: 'lyear',
        width: 80,
        align: 'right',
        customRender: ({ text }) => {
          const num = Number(text) || 0;
          return MathUtil.percent2DFormatter(num, 0);
        },
      },
      {
        title: '增长率',
        dataIndex: 'growthRate',
        key: 'growthRate',
        width: 80,
        align: 'right',
        customRender: ({ text }) => {
          const num = Number(text);
          return num != null && !isNaN(num) ? `${num.toFixed(0)}%` : '-';
        },
      },
    ];

    // 查询按钮
    const handleSearch = () => {
      fetchBaseInfo();
    };

    // 重置按钮：恢复昨天～昨天，关闭对比
    const handleReset = () => {
      currentDateRange.value = [dayjs().subtract(60, 'day'), dayjs().subtract(1, 'day')];
      contrastEnabled.value = false;
      currentContrastRange.value = [];
      fetchBaseInfo();
    };

    // 对比开关打勾时，自动把对比区间设为"选定时间区间往前推 1 年"
    const onContrastChange = (checked) => {
      if (checked) {
        const start = currentDateRange.value[0].clone();
        const end = currentDateRange.value[1].clone();
        currentContrastRange.value = [start.subtract(1, 'year'), end.subtract(1, 'year')];
      } else {
        currentContrastRange.value = [];
      }
    };

    // "筛选"弹窗点「保存」后，会拿到最新的字段配置，直接关闭弹窗并重新拉数据
    const confirmFilter = (selectedFields) => {
      filterFields.value = selectedFields;
      showFilter.value = false;
      fetchBaseInfo();
    };

    ////////////////////////////
    // 以下是各个"汇总行"函数，都加了 cols 校验：
    ////////////////////////////

    // "数据汇总"折叠面板的汇总行
    const hotelSummary = (cols) => {
      if (!Array.isArray(cols)) return [];
      const datas = summaryRankList.value;
      const record = cols.reduce((acc, col) => {
        acc[col.dataIndex] = ''; // 初始化所有字段
        return acc;
      }, {});
      cols.forEach((c, index) => {
        const key = c.dataIndex;
        console.log(key);
        record.name = '合计';
        if (index === 0) {
          record[key] = '合计';
        } else if (['revenue', 'contrastRevenue', 'revenueBudget'].includes(key)) {
          const sumVal = datas.reduce((s, item) => s + (item[key] || 0), 0);
          record[key] = MathUtil.currencyWFormatter(sumVal, 0);
        } else if (key === 'occRate') {
          const sumS = datas.reduce((s, item) => s + (item.actualSrooms || 0), 0);
          const sumC = datas.reduce((s, item) => s + (item.actualCrooms || 0), 0);
          record[key] = MathUtil.percent2DFormatter(MathUtil.safeDivide(sumS, sumC), 0);
        } else if (key === 'price') {
          const sumRoom = datas.reduce((s, item) => s + (item.roomRevenue || 0), 0);
          const sumS = datas.reduce((s, item) => s + (item.actualSrooms || 0), 0);
          record[key] = MathUtil.currencyWFormatter(MathUtil.safeDivide(sumRoom, sumS), 0);
        } else if (key === 'comMonthRate') {
          const sumMRev = datas.reduce((s, item) => s + (item.monthRevenue || 0), 0);
          const sumMBud = datas.reduce((s, item) => s + (item.monthBudget || 0), 0);
          record[key] = MathUtil.percent2DFormatter(MathUtil.safeDivide(sumMRev, sumMBud), 0);
        } else if (key === 'comRate') {
          const sumRev = datas.reduce((s, item) => s + (item.revenue || 0), 0);
          const sumRevBud = datas.reduce((s, item) => s + (item.revenueBudget || 0), 0);
          record[key] = MathUtil.percent2DFormatter(MathUtil.safeDivide(sumRev, sumRevBud), 0);
        } else if (key === 'lyear') {
          const sumLy = datas.reduce((s, item) => s + (item.lyearRevenue || 0), 0);
          record[key] = MathUtil.currencyWFormatter(sumLy, 0);
        } else if (key === 'growthRate') {
          const sumRev = datas.reduce((s, item) => s + (item.revenue || 0), 0);
          const sumLRev = datas.reduce((s, item) => s + (item.lyearRevenue || 0), 0);
          record[key] = MathUtil.diffPercent2Formatter(sumRev, sumLRev, 0);
        } else if (key === 'comYearRate') {
          const sumYRev = datas.reduce((s, item) => s + (item.yearRevenue || 0), 0);
          const sumYBud = datas.reduce((s, item) => s + (item.yearBudget || 0), 0);
          record[key] = MathUtil.percent2DFormatter(MathUtil.safeDivide(sumYRev, sumYBud), 0);
        }
      });
      return [record];
    };

    // "实际 vs 预算 vs 上年同期"这种通用表格的汇总行
    const hotelSummaryCommon = (cols, datas) => {
      if (!Array.isArray(cols)) return [];
      const record = {};
      cols.forEach((c, index) => {
        const key = c.dataIndex;
        if (index === 0) {
          record[key] = '合计';
        } else if (['actual', 'budget', 'lyear'].includes(key)) {
          const sumVal = datas.reduce((s, item) => s + (item[key] || 0), 0);
          record[key] = MathUtil.currencyWFormatter(sumVal, 0);
        } else if (key === 'comRate') {
          const sumBud = datas.reduce((s, item) => s + (item.budget || 0), 0);
          const sumAct = datas.reduce((s, item) => s + (item.actual || 0), 0);
          record[key] = MathUtil.percent2DFormatter(MathUtil.safeDivide(sumAct, sumBud), 0);
        } else if (key === 'growthRate') {
          const sumAct = datas.reduce((s, item) => s + (item.actual || 0), 0);
          const sumLy = datas.reduce((s, item) => s + (item.lyear || 0), 0);
          record[key] = MathUtil.diffPercent2Formatter(sumAct, sumLy, 0);
        }
      });
      return [record];
    };

    // 入住率的汇总行
    const hotelOcc = (cols) => {
      if (!Array.isArray(cols)) return [];
      const datas = occRankList.value;
      const record = {};
      cols.forEach((c, index) => {
        const key = c.dataIndex;
        if (index === 0) {
          record[key] = '合计';
        } else {
          const sumAS = datas.reduce((s, item) => s + (item.actualSrooms || 0), 0);
          const sumAC = datas.reduce((s, item) => s + (item.actualCrooms || 0), 0);
          const aOcc = MathUtil.safeDivide(sumAS, sumAC);
          const sumBS = datas.reduce((s, item) => s + (item.sroomsBudget || 0), 0);
          const sumBC = datas.reduce((s, item) => s + (item.croomsBudget || 0), 0);
          const bOcc = MathUtil.safeDivide(sumBS, sumBC);
          const sumLyS = datas.reduce((s, item) => s + (item.lyearActualSrooms || 0), 0);
          const sumLyC = datas.reduce((s, item) => s + (item.lyearActualCrooms || 0), 0);
          const lyOcc = sumLyC > 0 ? MathUtil.safeDivide(sumLyS, sumLyC) : 0;
          if (key === 'actual') {
            record[key] = MathUtil.percent2DFormatter(aOcc, 0);
          }
          if (key === 'budget') {
            record[key] = MathUtil.percent2DFormatter(bOcc, 0);
          }
          if (key === 'comRate') {
            record[key] = MathUtil.percent2DFormatter(MathUtil.safeDivide(aOcc, bOcc), 0);
          }
          if (key === 'lyear') {
            record[key] = MathUtil.percent2DFormatter(lyOcc, 0);
          }
          if (key === 'growthRate') {
            record[key] = MathUtil.diffPercent2Formatter(aOcc, lyOcc, 0);
          }
        }
      });
      return [record];
    };

    // 平均房价的汇总行
    const hotelPrice = (cols) => {
      if (!Array.isArray(cols)) return [];
      const datas = priceRankList.value;
      const record = {};
      cols.forEach((c, index) => {
        const key = c.dataIndex;
        if (index === 0) {
          record[key] = '合计';
        } else {
          const sumRR = datas.reduce((s, item) => s + (item.roomRevenue || 0), 0);
          const sumAS = datas.reduce((s, item) => s + (item.actualSrooms || 0), 0);
          const aPrice = MathUtil.safeDivide(sumRR, sumAS);
          const sumBR = datas.reduce((s, item) => s + (item.roomRevenueBudget || 0), 0);
          const sumBS = datas.reduce((s, item) => s + (item.sroomsBudget || 0), 0);
          const bPrice = MathUtil.safeDivide(sumBR, sumBS);
          const sumLyR = datas.reduce((s, item) => s + (item.lyearRoomRevenue || 0), 0);
          const sumLyS = datas.reduce((s, item) => s + (item.lyearActualSrooms || 0), 0);
          const lyPrice = MathUtil.safeDivide(sumLyR, sumLyS);
          if (key === 'actual') {
            record[key] = MathUtil.currencyWFormatter(aPrice, 0);
          }
          if (key === 'budget') {
            record[key] = MathUtil.currencyWFormatter(bPrice, 0);
          }
          if (key === 'comRate') {
            record[key] = MathUtil.percent2DFormatter(MathUtil.safeDivide(aPrice, bPrice), 0);
          }
          if (key === 'lyear') {
            record[key] = MathUtil.currencyWFormatter(lyPrice, 0);
          }
          if (key === 'growthRate') {
            record[key] = MathUtil.diffPercent2Formatter(aPrice, lyPrice, 0);
          }
        }
      });
      return [record];
    };

    // 每房收益的汇总行
    const hotelPerRevenue = (cols) => {
      if (!Array.isArray(cols)) return [];
      const datas = perRevenueRankList.value;
      const record = {};
      cols.forEach((c, index) => {
        const key = c.dataIndex;
        if (index === 0) {
          record[key] = '合计';
        } else {
          const sumRR = datas.reduce((s, item) => s + (item.roomRevenue || 0), 0);
          const sumAC = datas.reduce((s, item) => s + (item.actualCrooms || 0), 0);
          const aPerRev = MathUtil.safeDivide(sumRR, sumAC);
          const sumBR = datas.reduce((s, item) => s + (item.roomRevenueBudget || 0), 0);
          const sumBC = datas.reduce((s, item) => s + (item.croomsBudget || 0), 0);
          const bPerRev = MathUtil.safeDivide(sumBR, sumBC);
          const sumLyR = datas.reduce((s, item) => s + (item.lyearRoomRevenue || 0), 0);
          const sumLyC = datas.reduce((s, item) => s + (item.lyearActualCrooms || 0), 0);
          const lyPerRev = MathUtil.safeDivide(sumLyR, sumLyC);
          if (key === 'actual') {
            record[key] = MathUtil.currencyWFormatter(aPerRev, 0);
          }
          if (key === 'budget') {
            record[key] = MathUtil.currencyWFormatter(bPerRev, 0);
          }
          if (key === 'comRate') {
            record[key] = MathUtil.percent2DFormatter(MathUtil.safeDivide(aPerRev, bPerRev), 0);
          }
          if (key === 'lyear') {
            record[key] = MathUtil.currencyWFormatter(lyPerRev, 0);
          }
          if (key === 'growthRate') {
            record[key] = MathUtil.diffPercent2Formatter(aPerRev, lyPerRev, 0);
          }
        }
      });
      return [record];
    };

    // 根据是否跨天，以及是否打了"启动对比"，动态过滤"数据汇总"的列
    const getSummaryRankColumns = () => {
      let columns = [...summaryRankColumns];
      // 如果跨多天，就不展示"月进度""年进度"
      if (!currentDateRange.value[0].isSame(currentDateRange.value[1], 'day')) {
        columns = columns.filter((c) => !['comMonthRate', 'comYearRate'].includes(c.dataIndex));
      }
      // 如果没打"启动对比"，就不展示"对比收入"这一列
      if (!contrastEnabled.value) {
        columns = columns.filter((c) => c.dataIndex !== 'contrastRevenue');
      }
      return columns;
    };

    onMounted(() => {
      initHotelList();
    });

    return {
      loading,
      showFilter,
      currentDateRange,
      contrastEnabled,
      currentContrastRange,
      hotelList,
      summaryRankList,
      roomRankList,
      fbRankList,
      buffetRankList,
      cnRankList,
      spRankList,
      bhRankList,
      osRankList,
      otherRankList,
      occRankList,
      priceRankList,
      perRevenueRankList,
      tableHigh,
      filterFields,
      summaryRankColumns,
      rankColumns,
      occRankColumns,
      getSummaryRankColumns,
      hotelSummary,
      hotelSummaryCommon,
      hotelOcc,
      hotelPrice,
      hotelPerRevenue,
      handleSearch,
      handleReset,
      onContrastChange,
      confirmFilter,
    };
  },
};
</script>

<style lang="less" scoped>
.hotel-daily-main-project {
  width: 100%;
  height: 105px;
  font-weight: bold;
  line-height: 100px;
  text-align: center;
  background: #d3cee2;
  margin: 5px;
  font-size: 13px;
  padding: 5px;
}
.hotel-daily-main-right-0 {
  width: 100%;
  height: 100px;
  background: #fafafc;
  font-size: 13px;
}
.hotel-daily-m-main {
  display: flex;
  flex-direction: row;
  font-size: 13px;
  width: 1980px;
}
.hotel-daily-main-left {
  width: 100%;
  height: 30px;
  font-weight: bold;
  background: #d3cee2;
  margin: 5px;
  font-size: 13px;
  padding: 5px;
  text-align: center;
}
.hotel-daily-detail-0-1 {
  width: 100%;
  display: flex;
  flex-direction: row;
}
.hotel-daily-detail-0-2 {
  width: 100%;
  height: 30px;
  background: #d3cee2;
  margin: 2px 5px 0 0;
  line-height: 30px;
}
.hotel-daily-main-shouru-1-2-2 {
  width: 50%;
  height: 30px;
  background: #d3cee2;
  margin: 2px 0 0 0;
  line-height: 30px;
}
.hotel-daily-main-shouru-1-2-2 {
  width: 50%;
  height: 30px;
  background: #d3cee2;
  margin: 2px 0 0 0;
  line-height: 30px;
}
.hotel-daily-detail-0-2-2-first {
  width: 50%;
  height: 30px;
  background: #d3cee2;
  margin: 2px 0 0 0;
  line-height: 30px;
}
.hotel-daily-detail-0-2-2-first {
  width: 50%;
  height: 30px;
  background: #d3cee2;
  margin: 2px 0 0 0;
  line-height: 30px;
}
.hotel-daily-detail-0-2-2-last {
  width: 50%;
  height: 30px;
  background: #d3cee2;
  margin: 2px 0 0 5px;
  line-height: 30px;
}
.hotel-daily-detail-0-2-2 {
  width: 33%;
  height: 30px;
  background: #d3cee2;
  margin: 2px 0 0 0;
  line-height: 30px;
}
.hotel-daily-detail-0-2-3 {
  width: 33%;
  height: 30px;
  background: #d3cee2;
  margin: 2px 0 0 5px;
  line-height: 30px;
}
.hotel-daily-main-1-1 {
  width: 100%;
  height: 30px;
  background: #d3cee2;
  margin: 2px 5px 0 0;
  line-height: 30px;
}
.hotel-daily-main-1-1-2 {
  width: 100%;
  height: 30px;
  background: #d3cee2;
  margin: 2px 5px 0 0;
  line-height: 30px;
}
.hotel-daily-detial-1-1-2 {
  width: 100%;
  height: 30px;
  background: #e9e8ec;
  margin: 5px 5px 0 0;
  line-height: 30px;
  text-align: center;
}
.hotel-daily-main-shouru-1-1-2 {
  width: 50%;
  height: 30px;
  background: #d3cee2;
  margin: 2px 5px 0 0;
  line-height: 30px;
  text-align: center;
}
.hotel-daily-detial-1-2-last {
  width: 50%;
  height: 30px;
  background: #e9e8ec;
  margin: 5px 0 0 5px;
  line-height: 30px;
  text-align: center;
}
.hotel-daily-detial-1-2-first {
  width: 50%;
  height: 30px;
  background: #e9e8ec;
  margin: 5px 5px 0 0;
  line-height: 30px;
  text-align: center;
}
.hotel-daily-detial-1-2-2 {
  width: 50%;
  height: 30px;
  background: #e9e8ec;
  margin: 5px 5px 0 0;
  line-height: 30px;
  text-align: center;
}
.hotel-daily-detial-1-2-2-last {
  width: 50%;
  height: 30px;
  background: #e9e8ec;
  margin: 5px 0 0 5px;
  line-height: 30px;
  text-align: center;
}
.hotel-daily-detial-1-1-2-first {
  width: 50%;
  height: 30px;
  background: #e9e8ec;
  margin: 5px 5px 0 0;
  line-height: 30px;
  text-align: center;
}
.hotel-daily-main-1-2 {
  width: 33%;
  height: 30px;
  background: #d3cee2;
  margin: 2px 0 0 0;
  line-height: 30px;
}
.hotel-daily-main-1-2-2 {
  width: 50%;
  height: 30px;
  background: #d3cee2;
  margin: 2px 0 0 0;
  line-height: 30px;
}
.hotel-daily-main-1-3 {
  width: 33%;
  height: 30px;
  background: #d3cee2;
  margin: 2px 0 0 5px;
  line-height: 30px;
}
.hotel-daily-main-title0 {
  width: 100%;
  height: 100px;
  font-weight: bold;
  background: #fff;
  margin: 5px 0;
  font-size: 13px;
  text-align: center;
}
.hotel-daily-main-title {
  line-height: 30px;
  font-weight: bold;
  background: #d3cee2;
  font-size: 13px;
}
.hotel-daily-main-1-0 {
  width: 100%;
  display: flex;
  flex-direction: row;
  margin: 5px 0;
}
.hotel-daily-detial-1-1 {
  width: 33%;
  height: 30px;
  background: #e9e8ec;
  margin: 5px 5px 0 0;
  line-height: 30px;
  text-align: center;
}
.hotel-daily-detial-1-2 {
  width: 100%;
  height: 30px;
  background: #e9e8ec;
  margin: 5px 0 0 0;
  line-height: 30px;
  text-align: center;
}
.hotel-daily-detial-1-3 {
  width: 33%;
  height: 30px;
  background: #e9e8ec;
  margin: 5px 0 0 5px;
  line-height: 30px;
  text-align: center;
}

.hotel-daily-summary {
  display: flex;
  flex-direction: column;
  background-color: #fff;

  .top-section {
    background: #fff;
    padding: 24px 24px 0;
  }

  .header-wrapper {
    margin-bottom: 24px;

    .title {
      font-size: 18px;
      font-weight: 600;
      color: #1a253b;
      margin: 0;
      padding: 0;
    }
  }

  .form-wrapper {
    margin-bottom: 24px;

    .form-content {
      display: flex;
      align-items: center;
    }

    .form-item {
      flex: 1;
      display: flex;
      align-items: center;
      padding: 0 16px;

      &:first-child {
        padding-left: 0;
        justify-content: flex-end;
      }

      &:last-child {
        padding-right: 0;
      }

      .label {
        margin-right: 12px;
        color: rgba(0, 0, 0, 0.85);
        font-size: 14px;
      }
    }

    .form-item-center {
      justify-content: center;
    }

    .filter-icon-container {
      display: inline-block;
      padding: 4px;
      border-radius: 4px;
      transition: all 0.3s ease;
      margin-left: 10px;
    }

    .icon-screen {
      width: 20px;
      height: 20px;
      cursor: pointer;
      transition: all 0.3s ease;
      object-fit: scale-down;
    }

    .filter-icon-container:hover {
      background-color: #e1ebf9;
    }

    .icon-screen:hover {
      transform: scale(1.1);
      opacity: 0.8;
    }
  }

  .main-content {
    flex: 1;
    background: #f0f2f5;
    padding: 16px 0;
    overflow: auto;

    .card-flex-all {
      height: 100%;
    }

    &-title-custom {
      color: #00b578;
      font-weight: 500;
    }
  }

  .collapse-grid {
    display: flex;
    flex-wrap: wrap;
    gap: 16px;
  }

  .card-flex-all {
    flex: 1 1 100%;
    margin-bottom: 16px;
  }

  .card-flex {
    flex: 1 1 calc(50% - 16px);
    margin-bottom: 16px;
  }

  .mt-16 {
    margin-top: 16px;
  }
}

@media (max-width: 768px) {
  .card-flex {
    flex: 1 1 100%;
  }
}
</style>
